#include "stm32f10x.h"                  // Device header

extern uint16_t Num;

//定时器初始化
void Timer_Init(void)
{
	// 开启时钟
	RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE);
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
	// 选择时钟源
	TIM_ETRClockMode2Config(TIM2, TIM_ExtTRGPSC_OFF, TIM_ExtTRGPolarity_NonInverted, 0x0F);
	
	// 因为是外部时钟,所以配置GPIO让它进来
	// 配置GPIO口并初始化
	GPIO_InitTypeDef GPIO_InitStruture;
	GPIO_InitStruture.GPIO_Mode = GPIO_Mode_IPU;
	GPIO_InitStruture.GPIO_Pin = GPIO_Pin_0;
	GPIO_InitStruture.GPIO_Speed = GPIO_Speed_50MHz;
	GPIO_Init(GPIOA, &GPIO_InitStruture);
	
	//配置时基单元并初始化
	TIM_TimeBaseInitTypeDef Timer_BaseInitStruture;
	Timer_BaseInitStruture.TIM_ClockDivision = TIM_CKD_DIV1;          // 0x0000
	Timer_BaseInitStruture.TIM_CounterMode = TIM_CounterMode_Up;      // 向上计数
	Timer_BaseInitStruture.TIM_Period = 10-1;
	Timer_BaseInitStruture.TIM_Prescaler = 1-1;
	Timer_BaseInitStruture.TIM_RepetitionCounter = 0;
	TIM_TimeBaseInit(TIM2, &Timer_BaseInitStruture);
	
	//更新中断位使能 + 开启定时器
	TIM_ClearFlag(TIM2, TIM_FLAG_Update);						//清除定时器更新标志位
	TIM_ITConfig(TIM2, TIM_IT_Update, ENABLE);
	
	//中断分组
	NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2);
	
	//NVIC初始化并配置
	NVIC_InitTypeDef NVIC_InitStruture;
	NVIC_InitStruture.NVIC_IRQChannel = TIM2_IRQn;
	NVIC_InitStruture.NVIC_IRQChannelCmd = ENABLE;
	NVIC_InitStruture.NVIC_IRQChannelPreemptionPriority = 2;
	NVIC_InitStruture.NVIC_IRQChannelSubPriority = 1;
	NVIC_Init(&NVIC_InitStruture);
	
	TIM_Cmd(TIM2, ENABLE);
}

uint16_t Timer_GetCounter(void)
{
	return TIM_GetCounter(TIM2);	//返回定时器TIM2的CNT
}


//中断函数
void TIM2_IRQHandler(void)
{
	// 判断是不是真得触发
	if (TIM_GetITStatus(TIM2, TIM_IT_Update) == SET)
	{
		Num++;
		TIM_ClearITPendingBit(TIM2, TIM_IT_Update);		
	}
}
